<template>
  <n-card :bordered="false">
    <n-alert type="warning" class="alert_small m-b-10">
      温馨提示：1.每一个使用场景只能使用一个模板、其他模板自动会停用
      &nbsp;&nbsp;&nbsp;2.状态蓝色为启用、灰色为禁用状态。
    </n-alert>
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="searchParam" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="场景">
          <n-select v-model:value="searchParam.scene" :options="sceneOptions" style="width: 200px;" clearable/>
        </n-form-item>
        <n-form-item label="状态">
          <n-select v-model:value="searchParam.enable" :options="enableOptions" style="width: 130px;" clearable/>
        </n-form-item>
        <n-form-item>
          <search-button-group @submit="handleSubmitSearch"
                               @reset="()=>(searchParam.scene=null,searchParam.enable=null)"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list"
                :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="searchParam"
                list-url="sms_temp/list"
                default-serial-number
                serial-number-title="序号">
      <template #toolbarLeft>
        <n-button type="success" v-permission="['sms:temp:add']" @click="()=>(addEditModel=true)">
          <n-icon :size="18">
            <AddSharp/>
          </n-icon>
          新增
        </n-button>
      </template>
    </data-table>
    <!-- 新增、修改短信模板 -->
    <n-modal v-model:show="addEditModel"
             :title="addEditForm.id?'修改短信模板':'新增短信模板'" :mask-closable="false"
             style="width:560px;"
             :show-icon="false" preset="dialog" @after-leave="closeAddEditModel">
      <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
              label-width="auto" label-placement="left">
        <n-form-item label="模板编码" path="templateCode">
          <n-input v-model:value="addEditForm.templateCode" placeholder="请填写短信模板编码" clearable/>
        </n-form-item>
        <n-form-item label="短信签名" path="signName">
          <n-input v-model:value="addEditForm.signName" placeholder="请填写短信签名" clearable/>
        </n-form-item>
        <n-form-item label="使用场景" path="scene">
          <n-select v-model:value="addEditForm.scene" :options="sceneOptions" placeholder="请选择使用场景" clearable/>
        </n-form-item>
        <n-form-item label="模板内容" path="templateContent">
          <n-input v-model:value="addEditForm.templateContent"
                   placeholder="请填写短信模板内容"
                   type="textarea"
                   size="small"
                   :autosize="{minRows: 5,maxRows: 5}"
          />
        </n-form-item>
        <n-form-item label="备注" path="remark">
          <n-input v-model:value="addEditForm.remark"
                   placeholder="请填写备注"
                   type="textarea"
                   size="small"
                   :autosize="{minRows: 3,maxRows: 3}"
          />
        </n-form-item>
        <n-form-item label="状态" path="enable">
          <n-switch :round="false" v-model:value="addEditForm.enable" :checked-value="1" :unchecked-value="0">
            <template #checked>
              启用
            </template>
            <template #unchecked>
              停用
            </template>
          </n-switch>
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="()=>(addEditModel=false)">取消</n-button>
          <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>
<script setup lang="ts">
import {h, reactive, ref, computed} from 'vue'
import SearchButtonGroup from '@components/SearchButtonGroup';
import {SelectOption, NPopconfirm, FormInst, useMessage, NSwitch, FormItemRule} from 'naive-ui'
import DataTable from '@components/DataTable'
import DataTableAction from '@components/DataTable/src/components/DataTableAction';
import {delRequest, postPutRequest} from "@/api/data.ts";
import {AddSharp} from "@vicons/material";
import {permsJudg} from "@/util";

const message = useMessage()
//使用场景 0：注册  1：登录 2：支付成功通知 3：待支付通知 4：绑定电话通知 5：教师派遣通知
const sceneOptions = ref<SelectOption[]>([
  {
    label: '注册',
    value: 0,
  }, {
    label: '登录',
    value: 1,
  }, {
    label: '支付成功通知',
    value: 2,
  }, {
    label: '待支付通知',
    value: 3,
  }, {
    label: '绑定电话通知',
    value: 4,
  }, {
    label: '教师派遣通知',
    value: 5,
  }
]);
const enableOptions = ref<SelectOption[]>([
  {
    label: '启用',
    value: 1,
  }, {
    label: '停用',
    value: 0,
  }
]);

const searchParam = ref({
  scene: null,
  enable: null
});
//数据表
const data_list = ref<any>();
const columns = ref([
  {
    title: '短信签名',
    key: 'signName',
    width: 120,
  },
  {
    title: '模板编码',
    key: 'templateCode',
    width: 200,
  },
  {
    title: '场景',
    key: 'scene',
    width: 150,
    render(row: { scene: number }) {
      const scenes: SelectOption | any = sceneOptions.value.find(item => item.value === row.scene);
      return h('span', null, {default: () => (scenes && scenes.label || null)});
    }
  },
  {
    title: '模板内容',
    key: 'templateContent',
  }, {
    title: '备注',
    key: 'remark',
    width: 175,
  }, {
    title: '状态',
    key: 'enable',
    width: 80,
    align: 'center',
    render(row: { id: number, enable: number }) {
      return h(NSwitch, {
        round: false,
        checkedValue: 1,
        uncheckedValue: 0,
        value: row.enable,
        onUpdateValue: function (value) {
          if (permsJudg('sms:temp:enable')) { //权限 有权限进行一下操作
            row.enable = value;
            postPutRequest('sms_temp/up_enable', {
              id: row.id,
              enable: value
            }, 'PUT').then((result: ResponseResult) => {
              message.create(result.message, {
                type: result.code === 200 ? 'success' : 'error',
                duration: 1500,
                onLeave() {
                  data_list.value.reload();
                }
              });
              // row.enable = result.code === 200 ? value : value ? 0 : 1;
            })
          }
        }
      })
    }
  }, {
    title: '创建时间',
    key: 'createTime',
    width: 175,
  },
])
//操作列
const actionColumn = reactive({
  width: 120,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          permission: ['sms:temp:edit']
        },
        {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前短信模板吗？',
          },
          permission: ['sms:temp:del']
        },
      ]
    });
  },
});
//新增、修改短信模板
const addEditModel = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const handelSubmitLoading = ref<boolean>(false);
const addEditForm = ref({
  id: 0,
  templateCode: '',
  signName: '',
  scene: null,
  enable: 1,
  templateContent: '',
  remark: '',
})

const addEditFormRules = computed(() => {
  return {
    templateCode: {
      required: true,
      trigger: ['blur', 'input'],
      //message: '请填写短信模板编码',
      validator: (_rule: FormItemRule, value: string, callback: Function) => {
        const pattern = /^[a-zA-Z0-9_]*$/;
        if (value == null) {
          callback('请填写短信模板编码');
        } else if (!pattern.test(value)) {
          callback('请填写正确的短信模板编码');
        } else {
          callback();
        }
      }
    },
    signName:{
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写短信签名'
    },
    scene: {
      type: 'number',
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择所属场景'
    },
    templateContent: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请填写短信模板内容'
    }
  }
})


//查询模板
const handleSubmitSearch = () => {
  data_list.value.searchListData();
}
const handleEdit = (record: Recordable) => {
  addEditForm.value.id = record.id;
  addEditForm.value.templateCode = record.templateCode;
  addEditForm.value.scene = record.scene;
  addEditForm.value.enable = record.enable;
  addEditForm.value.templateContent = record.templateContent;
  addEditForm.value.remark = record.remark;
  addEditForm.value.signName = record.signName;
  addEditModel.value = true;
}
//删除模板
const handleDelete = (record: Recordable) => {
  delRequest('sms_temp/del', record.id).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
//关闭新增、修改短信模板
const closeAddEditModel = () => {
  addEditForm.value.id = 0;
  addEditForm.value.templateCode = '';
  addEditForm.value.scene = null;
  addEditForm.value.enable = 1;
  addEditForm.value.templateContent = '';
  addEditForm.value.remark = '';
  addEditForm.value.signName = '';
  handelSubmitLoading.value = false;
}
//提交新增、修改短信模板数据
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      const url = addEditForm.value.id ? 'sms_temp/edit' : 'sms_temp/add';
      postPutRequest(url, addEditForm.value, addEditForm.value.id ? 'PUT' : 'POST').then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditModel.value = false;
              if (addEditForm.value.id) {
                data_list.value.reload();
              } else {
                data_list.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
</script>

<style scoped lang="scss">

</style>